package com.fivebrms.hibernate.entity.business;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Iterator;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fivebrms.forms.w9.forms.RemoteConfidentialityForm;
import com.fivebrms.forms.w9.forms.RemoteIndependentForm;
import com.fivebrms.forms.w9.forms.RemoteLoginCredentials;
import com.fivebrms.hibernate.entity.dao.ConfidentialityFormDaoHibernate;
import com.fivebrms.hibernate.entity.dao.IndependentFormDaoHibernate;
import com.fivebrms.hibernate.entity.dao.LoginDaoHibernate;
import com.fivebrms.hibernate.entity.model.ConfidentialityForm;
import com.fivebrms.hibernate.entity.model.IndependentForm;
import com.fivebrms.hibernate.entity.model.LoginForm;

public class IndependentService
{
	final Logger	log	= LoggerFactory.getLogger(IndependentService.class);

	public RemoteIndependentForm submitIndependentForm(RemoteIndependentForm remoteIndependentForm)
	{
		log.info("login..ok successfully called the submitIndependentForm.. " + remoteIndependentForm);

		ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(flex.messaging.FlexContext
		        .getServletConfig().getServletContext());

		log.info("form created..2..");

		String independentSpringBean = "independentDAO";

		IndependentFormDaoHibernate independentDAO = (IndependentFormDaoHibernate) appContext.getBean(independentSpringBean);

		IndependentForm independentForm = new IndependentForm();
		try
		{
			BeanUtils.setProperty(independentForm, "contractorName", remoteIndependentForm.getContractorName());
			BeanUtils.setProperty(independentForm, "contractorAddress", remoteIndependentForm.getContractorAddress());
			BeanUtils.setProperty(independentForm, "dateSubmitted", new Timestamp(GregorianCalendar.getInstance()
			        .getTimeInMillis()));
		}
		catch (IllegalAccessException iae)
		{
			log.error("an error IllegalAccessException...", iae);
		}
		catch (InvocationTargetException ite)
		{
			log.error("an error occurred...", ite);
		}
		//
		// place the object into the database
		//
		independentDAO.createIndependentForm(independentForm);

		//
		// for now all confidentiality credentials are successfully submitted
		//
		remoteIndependentForm.setSubmitted(true);

		log.info("login..finished confidentiality successfully.. ");

		log.info("login looking..size-->" + independentDAO.findAll().size());

		return remoteIndependentForm;
	}

}
